package com.ruoyi.business.modbus.service.modbus4j;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.ruoyi.business.modbus.domain.ModbusMasterDevice;
import com.ruoyi.business.modbus.domain.ModbusRtuMasterDevice;
import com.ruoyi.business.modbus.service.IModbusCoreService;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.serial.SerialPortWrapper;

/**
 * Modbus4J RTU服务实现类
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@Service("modbus4jRtuService")
public class Modbus4jRtuServiceImpl extends AbstractModbus4jService implements IModbusCoreService
{
    @Override
    protected ModbusMaster createModbusMaster(ModbusMasterDevice modbusMasterEntity) throws Exception
    {
        if (!(modbusMasterEntity instanceof ModbusRtuMasterDevice)) {
            throw new IllegalArgumentException("设备类型必须是ModbusRtuMasterDevice");
        }
        
        ModbusRtuMasterDevice rtuDevice = (ModbusRtuMasterDevice) modbusMasterEntity;
        
        // 创建串口包装器
        SerialPortWrapper wrapper = new com.ruoyi.business.modbus.serial.jserialcomm.JSerialCommSerialPortWrapper(
            rtuDevice.getSerialPort(), 
            rtuDevice.getBaudRate(), 
            rtuDevice.getDataBits(), 
            rtuDevice.getStopBits(), 
            convertParityStringToInt(rtuDevice.getParity())
        );
        
        // 创建Modbus工厂和RTU主站
        ModbusFactory factory = new ModbusFactory();
        ModbusMaster master = factory.createRtuMaster(wrapper);
        
        // 初始化主站
        master.init();
        
        return master;
    }
    
    /**
     * 将校验位字符串转换为整数值
     */
    private int convertParityStringToInt(String parity) {
        if (parity == null) {
            return 0; // NONE
        }
        
        switch (parity.toUpperCase()) {
            case "NONE":
                return 0;
            case "ODD":
                return 1;
            case "EVEN":
                return 2;
            case "MARK":
                return 3;
            case "SPACE":
                return 4;
            default:
                return 0; // 默认NONE
        }
    }
    
    @Override
    public Map<String, Object> getImplementationInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("implementation", "Modbus4jRtuServiceImpl");
        info.put("type", "RTU");
        info.put("description", "Modbus4J RTU服务实现，使用jSerialComm库");
        info.put("version", "1.0");
        return info;
    }
}
